<template>
  <div class="centerRight2">
    <div class="bg-color-black">
      <div class="d-flex pt-2 pl-2">
        <span>
          <i class="iconfont icon-vector" />
        </span>
        <div class="d-flex">
          <span class="fs-xl text mx-2">电池情况</span>
        </div>
      </div>
      <div class="d-flex mt-1 jc-center body-box">
        <div class="batteryItem">
          <div class="item">
            <span>总容量</span>
            <chart
                :tips="rate[0].tips"
                :colorObj="rate[0].colorData"
                :currentCapacity="rate[0].currentCapacity"
            />
          </div>
          <div class="item">
            <span>剩余容量</span>
            <chart
                :tips="rate[1].tips"
                :colorObj="rate[1].colorData"
                :currentCapacity="rate[1].currentCapacity"
            />
          </div>
        </div>
        <dv-scroll-board class="dv-scr-board" :config="config" />
      </div>
    </div>
  </div>
</template>

<script>
import {computed, defineComponent, reactive, ref, watch} from 'vue'
import Chart from "@/views/center/chart/draw";
import {useWebSocketStore} from "@/store/websocket";
import {useStore} from "vuex";
export default defineComponent({
  components: {Chart},
  setup() {
    const wsStore = useWebSocketStore();
    const store = useStore()
    const strategy = computed(() => {console.log('策略:', strategy.value) ;return store.getters.currentStrategy;}) // 策略
    const capacity = computed(() => wsStore.totalEnergy || []);
    const hours = computed(() => wsStore.cdata[strategy.value].hours || []);
    const chargeStatus = computed(() => wsStore.cdata[strategy.value].chargeStatus);
    const batteryNowCapacity = computed(() => wsStore.cdata[strategy.value].batteryEnergy)
    const currentCapacity = ref(null);
    watch(strategy, (newStrategy) => {
      const batteryEnergy = wsStore.cdata[newStrategy]?.batteryEnergy || [];
      // console.log('右边显示电池容量变化:', batteryEnergy);
      currentCapacity.value = batteryEnergy.length > 0
          ? batteryEnergy[batteryEnergy.length - 1]
          : null;
      console.log('剩余电池容量百分比:', currentCapacity.value);
    }, { immediate: true }); // immediate: true 是为了初始化时也能执行一次
    const config = reactive({
      header: ['时刻', '充放电', '剩余电量百分比'],
      data: computed(() => {
        // 确保三个数组长度一致
        const minLength = Math.min(
            hours.value.length,
            chargeStatus.value.length,
            batteryNowCapacity.value.length
        );

        return Array.from({ length: minLength }, (_, i) => {
          // 根据chargeStatus的值确定充放电状态文字
          const statusText =
              chargeStatus.value[i] > 0 ? '充电' :
                  chargeStatus.value[i] < 0 ? '放电' : '--';

          const formattedValue = Number.isNaN(batteryNowCapacity.value[i])
              ? '--'
              : batteryNowCapacity.value[i].toFixed(2) + '%';
          return [
            hours.value[i] || '--',  // 时刻
            statusText,              // 充放电状态
            formattedValue  // 当前容量
          ];
        });
      }),
      rowNum: 7, //表格行数
      headerHeight: 35,
      headerBGC: '#0f1325', //表头
      oddRowBGC: '#0f1325', //奇数行
      evenRowBGC: '#171c33', //偶数行
      index: false,
      columnWidth: [80,70,130],
      align: ['center', 'center', 'center']
    })
    const rateColorData = [
      {
        textStyle: '#3fc0fb',
        series: {
          color: ['#00bcd44a', 'transparent'],
          dataColor: {
            normal: '#03a9f4',
            shadowColor: '#97e2f5'
          }
        }
      },
      {
        textStyle: '#67e0e3',
        series: {
          color: ['#faf3a378', 'transparent'],
          dataColor: {
            normal: '#ff9800',
            shadowColor: '#fcebad'
          }
        }
      }
    ]
    const rate = reactive([
      {
        id: 'centerRate1',
        tips: Number(capacity.value) || 0,
        colorData: rateColorData[0],
        currentCapacity:100
      },
      {
        id: 'centerRate2',
        tips: computed(() => Number(((currentCapacity.value || 0) * capacity.value / 100).toFixed(2)) || 0),
        colorData: rateColorData[1],
        currentCapacity: computed(() => currentCapacity.value)
      }
    ])
    // // 加载状态
    // const isLoading = ref(false)
    // // 错误信息
    // const error = ref('')
    // 从后端获取rate数据
    // const fetchRateData = async () => {
    //   isLoading.value = true
    //   error.value = ''
    //   getEnvInfo(1)
    //       .then(res => {
    //         // 假设返回格式为 { batteryCapacity: 60, currentCapacity: 40 }
    //         const rateData = res.data;
    //         console.log('获取电池数据成功:', rateData);
    //         // 更新rate数据，保持colorData不变
    //         rate[0].tips = rateData.data.capacity || 0;
    //         rate[1].tips = rateData.data.capacity || 0;
    //       })
    //       .catch(err => {
    //         error.value = err.message || '获取数据失败';
    //         console.error('获取电池数据失败:', err);
    //       })
    //       .finally(() => {
    //         isLoading.value = false;
    //       });
    //
    // }
    return { config ,rate}
  }
})
</script>

<style lang="scss" scoped>
$box-height: 410px;
$box-width: 300px;
.centerRight2 {
  padding: 16px;
  padding-top: 20px;
  height: $box-height;
  width: $box-width;
  border-radius: 5px;
  .bg-color-black {
    height: $box-height - 30px;
    border-radius: 10px;
  }
  .text {
    font-size: 15px;
    color: #c3cbde;
  }
  .body-box {
    flex-direction: column;
    border-radius: 10px;
    overflow: hidden;
    .dv-scr-board {
      width: 270px;
      height: 220px;
    }
  }
}
.batteryItem {
  display: flex;
  justify-content: space-between;
  align-items: center;
  .item {
    text-align: center;
    justify-content: center;
    align-items: center;
  }
}
</style>
